package com.fary.impl;

import cn.hutool.core.util.StrUtil;
import com.fary.dto.PayMerchantQrCodeRespDTO;
import com.fary.service.PayMerchantQrCodeService;
import com.fary.util.TokenUtils;
import com.fary.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.fary.constant.PayConstant.QRCODE_EXPIRE_SECONDS;

@Service
@Slf4j
public class PayMerchantQrCodeServiceImpl implements PayMerchantQrCodeService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private WxMpService wxMpService;

    @Override
    public PayMerchantQrCodeRespDTO generateQrCode() {
        // 1.生成 二维码对应token
        String sceneIdStr = TokenUtils.getToken();
        try {
            // 2.生成二维码
            WxMpQrCodeTicket wxMpQrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(sceneIdStr, QRCODE_EXPIRE_SECONDS);
            String url = wxMpQrCodeTicket.getUrl();
            return new PayMerchantQrCodeRespDTO(sceneIdStr, url);
        } catch (Exception e) {
            log.error("e:{}", e);
            return null;
        }
    }

    public boolean scanningRelevanceOpenId(WxMpXmlMessage wxMpXmlMessage) {
        // 扫码事件处理
        // 1.获取二维码中的参数
        String eventKey = wxMpXmlMessage.getEventKey();
        if (StrUtil.isEmpty(eventKey)) {
            return Boolean.FALSE;
        }
        //2.获取用户的openid
        String openId = wxMpXmlMessage.getFromUser();
        //3.redis中记录该key用户对应的openid
        redisCache.setCacheObject(eventKey, openId);
        return Boolean.TRUE;
    }

    @Override
    public boolean getQrCodeTokenResult(String qrCodeToken) {
        //从Redis中获取商家的openid
        String merchantOpenId = redisCache.getCacheObject(qrCodeToken);
        return !StrUtil.isEmpty(merchantOpenId) ? Boolean.TRUE : Boolean.FALSE;
    }
}
